package cn.com.ccxe.service;

import java.util.List;

import cn.com.ccxe.core.crawl.CrawlExpressionCache;
import cn.com.ccxe.core.entity.CrawlExpression;
import cn.com.ccxe.core.entity.Website;
import cn.com.ccxe.dao.OperationStatus;
import cn.com.ccxe.dao.WebsiteDao;
import cn.com.ccxe.dao.impl.WebsiteDaoImpl;

public class WebsiteBussiness {

	private WebsiteDao moduleDao = new WebsiteDaoImpl();
	
	public OperationStatus del(int moduleId) {
		if(moduleId <= 0) {
			throw new RuntimeException("moduleId="+moduleId+",无法删除！");
		}
		//查看是否有子模块，如果有就不删除。
		if(moduleDao.countChild(moduleId) >0 )  {
			return OperationStatus.RELATIONSHIP_EMPTY;
		}
		//FIXME 还需进行事务异常处理。
		CrawlExpressionCache.remove(moduleId);
		return moduleDao.del(moduleId);
	}
	
	public OperationStatus add(Website module) {
		if(module == null) {
			throw new NullPointerException("传入的模块为空！");
		}
		int id = moduleDao.addAndRetuenId(module);
		CrawlExpression rule = module.getListPage();
		if(rule != null && id >0) {
			rule.setModuleId(id);
			return CrawlExpressionCache.put(rule.getModuleId(),rule);
		}
		if(id > 0) {
			return OperationStatus.SUCCESS;
		}else {
			return OperationStatus.FAILURE;
		}
	}
	
	public OperationStatus update(Website module) {
		if(module == null) {
			throw new NullPointerException("传入的模块为空！");
		}
		int subWebsiteNum = moduleDao.countSubWebsite(module.getId());
		if(subWebsiteNum > 0) {
			return OperationStatus.RELATIONSHIP_EMPTY;
		}
		CrawlExpression rule = module.getListPage();
		if(rule != null ) {
			CrawlExpressionCache.put(rule.getModuleId(),rule);
		}
		return moduleDao.update(module);
	}
	
	public Website get(int id) {
		if(id <= 0) {
			throw new RuntimeException("错误：moduleId="+id+"！");
		}
		return moduleDao.get(id);
	}
	
	public List<Website> getTopWebsite() {
		return moduleDao.getTopWebsite();
		
	}
	public List<Website> getChildWebsite(int parentId) {
		if(parentId < 0) {
			throw new RuntimeException("错误：ID小于零！");
		}
		return moduleDao.getChildWebsite(parentId);
	}
	
	public int getParentWebsiteId(int id) {
		if(id <= 0) {
			return 0;//直接为顶级模块
		}
		return moduleDao.getParentWebsiteId(id);
	}

	public CrawlExpression getRule(int id) {
		if(id <= 0) {
			throw new RuntimeException("错误：website id="+id+"！");
		}
		return CrawlExpressionCache.get(id);
	}

}
